package entity

import (
	"github.com/gorilla/websocket"
	"time"
)

const oneSecond = 1000
const readMsgCountPerSecond = 16

type UserSession struct {
	userID        uint32
	clientIPAddr  string
	conn          *websocket.Conn
	clientMsgChan chan []byte
	sessionID     uint32
	createdAt     time.Time
}

func NewUserSession(sessionID uint32, conn *websocket.Conn, clientIP string) *UserSession {
	return &UserSession{
		sessionID:     sessionID,
		conn:          conn,
		clientIPAddr:  clientIP,
		clientMsgChan: make(chan []byte, 64),
		createdAt:     time.Now(),
	}
}

func (us *UserSession) GetUserID() uint32 {
	return us.userID
}

func (us *UserSession) BindUserID(userID uint32) {
	us.userID = userID
}

func (us *UserSession) GetSessionID() uint32 {
	return us.sessionID
}

func (us *UserSession) GetClientIPAddr() string {
	return us.clientIPAddr
}

func (us *UserSession) GetConnection() *websocket.Conn {
	return us.conn
}

func (us *UserSession) GetClientMsgChan() chan []byte {
	return us.clientMsgChan
}

func (us *UserSession) GetCreatedAt() time.Time {
	return us.createdAt
}

func (us *UserSession) Write(msgObj []byte) {
	if msgObj == nil || us.conn == nil || us.clientMsgChan == nil {
		return
	}
	us.clientMsgChan <- msgObj
}

func (us *UserSession) Disconnect() error {
	if us.conn == nil {
		return nil
	}
	return us.conn.Close()
}

// ReadMessage 基本的消息读取功能，不包含业务逻辑
func (us *UserSession) ReadMessage() (messageType int, data []byte, err error) {
	if us.conn == nil {
		return 0, nil, nil
	}
	return us.conn.ReadMessage()
}

// WriteMessage 基本的消息写入功能
func (us *UserSession) WriteMessage(messageType int, data []byte) error {
	if us.conn == nil {
		return nil
	}
	return us.conn.WriteMessage(messageType, data)
}

// SetReadLimit 设置读取限制
func (us *UserSession) SetReadLimit(limit int64) {
	if us.conn != nil {
		us.conn.SetReadLimit(limit)
	}
}
